<template>
  <div class="device-container">
    <!-- 功能切换选项卡（仅保留设备管理） -->
    <el-radio-group v-model="activeTab" style="margin-bottom: 20px">
      <el-radio value="device">设备管理</el-radio>
    </el-radio-group>

    <!-- 设备管理：筛选区域 -->
    <div class="filter-bar">
      <el-select
          v-model="selectedFilter"
          placeholder="选择筛选维度"
          clearable
          style="width: 140px; margin-right: 8px"
      >
        <el-option
            v-for="(item, idx) in filterOptions"
            :key="idx"
            :label="item.label"
            :value="item.value"
        />
      </el-select>
      <el-input
          v-model="filterValue"
          placeholder="请输入内容"
          clearable
          @keyup.enter="handleSearch"
          style="width: 200px; margin-right: 8px"
      />
      <el-select
          v-model="deviceStatusFilter"
          placeholder="设备状态"
          clearable
          style="width: 120px; margin-right: 8px"
      >
        <el-option
            v-for="(status, idx) in statusOptions"
            :key="idx"
            :label="status.label"
            :value="status.value"
        />
      </el-select>
      <el-button type="primary" @click="handleSearch">查询</el-button>
      <el-button @click="handleReset">重置</el-button>
      <el-button type="primary" icon="plus" @click="openDeviceDialog()">新增</el-button>
      <el-button icon="delete" style="margin-left: 10px;" :disabled="!multipleDeviceSelection.length" @click="deleteSelectedDevices">批量删除</el-button>
    </div>

    <!-- 加载状态反馈 -->
    <el-skeleton :loading="loading" :count="10" style="margin-top: 16px;">
      <!-- 设备管理表格 -->
      <el-table
          :data="tableData"
          border
          style="width: 100%; margin-top: 16px"
          @selection-change="handleDeviceSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="device_sn" label="设备编号" width="120" />
        <el-table-column prop="device_name" label="设备名称" width="120" />
        <el-table-column prop="device_type" label="设备分类" width="120" />
        <el-table-column prop="device_address" label="设备地址" width="120" />
        <el-table-column
            prop="device_status"
            label="设备状态"
            width="120"
            align="center"
        >
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.device_status)">
              {{ DeviceStatusMap[scope.row.device_status] || scope.row.device_status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="device_version" label="设备版本" width="120" />
        <el-table-column
            prop="device_after_sales"
            label="售后负责人"
            width="120"
        />
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="scope">
            <el-button
                type="text"
                icon="el-icon-view"
                @click="viewDeviceDetails(scope.row)"
            >
              查看
            </el-button>
            <el-button
                type="text"
                icon="el-icon-edit"
                @click="editDevice(scope.row)"
            >
              编辑
            </el-button>
            <el-button
                type="text"
                icon="el-icon-delete"
                @click="deleteDevice1(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-skeleton>

    <!-- 分页 -->
    <el-pagination
        :total="total"
        :page-size="pageSize"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
        style="margin-top: 16px; text-align: right"
    />

    <!-- 设备管理：操作弹窗 -->
    <el-drawer
        destroy-on-close
        :size="appStore.drawerSize"
        v-model="deviceDialogVisible"
        :show-close="false"
        :before-close="closeDeviceDialog"
    >
      <template #header>
        <div class="flex justify-between items-center">
          <span class="text-lg">{{ deviceDialogType === 'create' ? '新增设备' : '编辑设备' }}</span>
          <div>
            <el-button :loading="deviceBtnLoading" type="primary" @click="saveDevice">
              确 定
            </el-button>
            <el-button @click="closeDeviceDialog">取 消</el-button>
          </div>
        </div>
      </template>
      <el-form
          :model="deviceForm"
          label-position="top"
          ref="deviceFormRef"
          :rules="deviceRules"
          label-width="80px"
      >
        <el-form-item label="设备编号:" prop="device_sn">
          <el-input
              v-model="deviceForm.device_sn"
              :clearable="true"
              placeholder="请输入设备编号"
          />
        </el-form-item>
        <el-form-item label="设备名称:" prop="device_name">
          <el-input
              v-model="deviceForm.device_name"
              :clearable="true"
              placeholder="请输入设备名称"
          />
        </el-form-item>
        <el-form-item label="设备分类:" prop="device_type">
          <el-input
              v-model="deviceForm.device_type"
              :clearable="true"
              placeholder="请输入设备分类"
          />
        </el-form-item>
        <el-form-item label="设备地址:" prop="device_address">
          <!-- 省 -->
          <el-select
              v-model="selectedProvince"
              placeholder="请选择省"
              @change="handleProvinceChange"
              style="margin-right: 8px; width: 120px"
          >
            <el-option
                v-for="item in provinceList"
                :key="item.code"
                :label="item.name"
                :value="item.code.toString()"
            />
          </el-select>
          <!-- 市 -->
          <el-select
              v-model="selectedCity"
              placeholder="请选择市"
              :disabled="!selectedProvince"
              @change="handleCityChange"
              style="margin-right: 8px; width: 120px"
          >
            <el-option
                v-for="item in cityOptions"
                :key="item.code"
                :label="item.name"
                :value="item.code.toString()"
            />
          </el-select>
          <!-- 区 -->
          <el-select
              v-model="selectedDistrict"
              placeholder="请选择区"
              :disabled="!selectedCity"
              @change="handleDistrictChange"
              style="margin-right: 8px; width: 120px"
          >
            <el-option
                v-for="item in districtOptions"
                :key="item.code"
                :label="item.name"
                :value="item.code.toString()"
            />
          </el-select>
          <!-- 县/街道 -->
          <el-select
              v-model="selectedCounty"
              placeholder="请选择县/街道"
              :disabled="!selectedDistrict"
              @change="handleCountyChange"
              style="margin-right: 8px; width: 120px"
          >
            <el-option
                v-for="item in countyOptions"
                :key="item.code"
                :label="item.name"
                :value="item.code.toString()"
            />
          </el-select>
          <!-- 乡/社区 -->
          <el-select
              v-model="selectedTown"
              placeholder="请选择乡/社区"
              :disabled="!selectedCounty"
              style="width: 120px"
          >
            <el-option
                v-for="item in townOptions"
                :key="item.code"
                :label="item.name"
                :value="item.code.toString()"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="设备状态:" prop="device_status">
          <el-select v-model="deviceForm.device_status" placeholder="选择设备状态">
            <el-option
                v-for="(status, idx) in statusOptions"
                :key="idx"
                :label="status.label"
                :value="status.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="设备版本:" prop="device_version">
          <el-input
              v-model="deviceForm.device_version"
              :clearable="true"
              placeholder="请输入设备版本"
          />
        </el-form-item>
        <el-form-item label="售后负责人:" prop="device_after_sales">
          <el-input
              v-model="deviceForm.device_after_sales"
              :clearable="true"
              placeholder="请输入售后负责人"
          />
        </el-form-item>
      </el-form>
    </el-drawer>

    <!-- 详情弹窗 -->
    <el-drawer
        destroy-on-close
        :size="appStore.drawerSize"
        v-model="detailVisible"
        :show-close="true"
        :before-close="closeDetail"
        title="查看详情"
    >
      <el-descriptions :column="1" border>
        <el-descriptions-item label="设备编号">
          {{ detailData.device_sn }}
        </el-descriptions-item>
        <el-descriptions-item label="设备名称">
          {{ detailData.device_name }}
        </el-descriptions-item>
        <el-descriptions-item label="设备分类">
          {{ detailData.device_type }}
        </el-descriptions-item>
        <el-descriptions-item label="设备地址">
          {{ detailData.device_address }}
        </el-descriptions-item>
        <el-descriptions-item label="设备状态">
          {{ DeviceStatusMap[detailData.device_status] || detailData.device_status }}
        </el-descriptions-item>
        <el-descriptions-item label="设备版本">
          {{ detailData.device_version }}
        </el-descriptions-item>
        <el-descriptions-item label="售后负责人">
          {{ detailData.device_after_sales }}
        </el-descriptions-item>
      </el-descriptions>
    </el-drawer>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick, watch } from 'vue'
import {
  ElMessage,
  ElMessageBox,
  ElSkeleton,
  ElSelect,
  ElOption,
  ElInput,
  ElButton,
  ElTable,
  ElTableColumn,
  ElPagination,
  ElForm,
  ElFormItem,
  ElDrawer,
  ElDescriptions,
  ElDescriptionsItem,
  ElRadioGroup,
  ElRadio,
  ElTag
} from 'element-plus'
import axios from 'axios'
import { useAppStore } from '@/pinia'

// 全局状态（省/市/区/县/乡数据）
const provinceList = ref([])   // 省级数据
const cityOptions = ref([]);   // 市级选项
const districtOptions = ref([]); // 区级选项
const countyOptions = ref([]);  // 县级选项
const townOptions = ref([]);   // 乡级选项

const cityMap = ref({});        // 市级数据：{ 省code: [] }
const districtMap = ref({});    // 区级数据：{ 市code: [] }
const countyMap = ref({});      // 县级数据：{ 区code: [] }
const townMap = ref({});        // 乡级数据：{ 县code: [] }

// 选择器绑定值
const selectedProvince = ref('')
const selectedCity = ref('')
const selectedDistrict = ref('')
const selectedCounty = ref('')
const selectedTown = ref('')

// 初始化省市区数据
const initAreaData = async () => {
  try {
    const res = await axios.get('/pcas-code.json');
    let pcasData = res.data;

    // 确保数据是数组格式
    if (!Array.isArray(pcasData)) {
      if (pcasData.data && Array.isArray(pcasData.data)) {
        pcasData = pcasData.data;
      } else {
        console.error('省市区数据格式错误:', pcasData);
        ElMessage.error('省市区数据格式错误，请检查');
        return;
      }
    }

    // 提取省级数据
    provinceList.value = pcasData.map(province => ({
      code: province.code.toString(),
      name: province.name,
    }));

    // 构建映射关系
    const buildMap = (parentCode, children, level) => {
      if (!children || !Array.isArray(children)) return;

      children.forEach(item => {
        const { code, name, children: subChildren = [] } = item;
        if (!code || !name) return;

        const codeStr = code.toString();

        // 根据层级存入 Map
        if (level === 2) cityMap.value[parentCode] = cityMap.value[parentCode] || [];
        if (level === 3) districtMap.value[parentCode] = districtMap.value[parentCode] || [];
        if (level === 4) countyMap.value[parentCode] = countyMap.value[parentCode] || [];
        if (level === 5) townMap.value[parentCode] = townMap.value[parentCode] || [];

        if (level === 2) cityMap.value[parentCode].push({ code: codeStr, name });
        else if (level === 3) districtMap.value[parentCode].push({ code: codeStr, name });
        else if (level === 4) countyMap.value[parentCode].push({ code: codeStr, name });
        else if (level === 5) townMap.value[parentCode].push({ code: codeStr, name });

        // 递归处理子级
        buildMap(codeStr, subChildren, level + 1);
      });
    };

    // 从省级开始遍历
    pcasData.forEach(province => {
      buildMap(province.code.toString(), province.children, 2);
    });

    console.log('省市区数据初始化完成');
  } catch (error) {
    console.error('加载省市区数据失败:', error);
    ElMessage.error('省市区数据加载失败，请联系管理员');
  }
};

// 选择器联动逻辑
const handleProvinceChange = (provinceCode) => {
  selectedCity.value = '';
  selectedDistrict.value = '';
  selectedCounty.value = '';
  selectedTown.value = '';

  // 使用深拷贝确保响应式更新
  cityOptions.value = JSON.parse(JSON.stringify(cityMap.value[provinceCode] || []));
};

const handleCityChange = (cityCode) => {
  selectedDistrict.value = '';
  selectedCounty.value = '';
  selectedTown.value = '';

  districtOptions.value = JSON.parse(JSON.stringify(districtMap.value[cityCode] || []));
};

const handleDistrictChange = (districtCode) => {
  selectedCounty.value = '';
  selectedTown.value = '';

  countyOptions.value = JSON.parse(JSON.stringify(countyMap.value[districtCode] || []));
};

const handleCountyChange = (countyCode) => {
  selectedTown.value = '';

  townOptions.value = JSON.parse(JSON.stringify(townMap.value[countyCode] || []));
};

// 全局状态
const appStore = useAppStore()
const activeTab = ref('device')
const loading = ref(false)

// 设备管理状态相关
const filterOptions = ref([
  { label: '设备编号', value: 'device_sn' },
  { label: '设备名称', value: 'device_name' },
  { label: '设备分类', value: 'device_type' },
  { label: '设备地址', value: 'device_address' },
  { label: '设备版本', value: 'device_version' },
  { label: '售后负责人', value: 'device_after_sales' },
])
const selectedFilter = ref('device_sn')
const filterValue = ref('')
const deviceStatusFilter = ref('')
const tableData = ref([])
const total = ref(0)
const pageSize = ref(10)
const currentPage = ref(1)
const multipleDeviceSelection = ref([])
const deviceDialogVisible = ref(false)
const deviceDialogType = ref('create')
const deviceBtnLoading = ref(false)
const deviceForm = ref({
  device_sn: '',
  device_name: '',
  device_type: '',
  device_address: '',
  device_status: '1',
  device_version: '',
  device_after_sales: '',
})
const deviceFormRef = ref(null)
const deviceRules = reactive({
  device_sn: [
    { required: true, message: '请输入设备编号', trigger: 'blur' },
  ],
  device_name: [
    { required: true, message: '请输入设备名称', trigger: 'blur' },
  ],
})
const detailVisible = ref(false)
const detailData = ref({})

// 设备状态选项及映射
const statusOptions = ref([
  { label: '进行中', value: '1' },
  { label: '已停止', value: '2' },
  { label: '异常', value: '3' },
])
const DeviceStatusMap = {
  '1': '进行中',
  '2': '已停止',
  '3': '异常',
}

// 获取设备状态标签类型
const getStatusTagType = (status) => {
  switch (status) {
    case '1':
      return 'success'
    case '2':
      return 'warning'
    case '3':
      return 'danger'
    default:
      return 'info'
  }
}

const fetchDeviceList = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
      [selectedFilter.value]: filterValue.value,
      device_status: deviceStatusFilter.value,
    }
    const res = await axios.get('/api/device/SearchDevice', { params })
    // 原来判断是200，现在兼容code为0的情况
    if (res.data.code === 200 || res.data.code === 0) {
      tableData.value = res.data.data.list || []
      total.value = res.data.data.total || 0
    } else {
      ElMessage.error(res.data.msg || '获取设备列表失败')
    }
  } catch (error) {
    console.error('请求失败:', error)
    ElMessage.error('网络异常，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 搜索设备
const handleSearch = () => {
  currentPage.value = 1
  fetchDeviceList()
}

// 重置搜索
const handleReset = () => {
  selectedFilter.value = 'device_sn'
  filterValue.value = ''
  deviceStatusFilter.value = ''
  currentPage.value = 1
  fetchDeviceList()
}

// 分页变化
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchDeviceList()
}
const handlePageChange = (val) => {
  currentPage.value = val
  fetchDeviceList()
}

// 设备选择变化
const handleDeviceSelectionChange = (val) => {
  multipleDeviceSelection.value = val
}

// 打开弹窗
const openDeviceDialog = () => {
  deviceDialogType.value = 'create'

  // 重置表单和选择器
  deviceForm.value = {
    device_sn: '',
    device_name: '',
    device_type: '',
    device_address: '',
    device_status: '1',
    device_version: '',
    device_after_sales: '',
  }

  selectedProvince.value = ''
  selectedCity.value = ''
  selectedDistrict.value = ''
  selectedCounty.value = ''
  selectedTown.value = ''

  deviceDialogVisible.value = true

  nextTick(() => {
    deviceFormRef.value?.resetFields()
  })
}

// 编辑设备
const editDevice = (row) => {
  deviceDialogType.value = 'update'

  // 深拷贝避免引用问题
  deviceForm.value = JSON.parse(JSON.stringify(row))

  // 地址回显逻辑
  const address = row.device_address || {}

  // 处理不同格式的地址数据
  if (typeof address === 'string') {
    // 如果地址是字符串，可能需要拆分或跳过回显
    console.warn('设备地址是字符串格式，无法自动回显到选择器')
    selectedProvince.value = ''
    selectedCity.value = ''
    selectedDistrict.value = ''
    selectedCounty.value = ''
    selectedTown.value = ''
  } else {
    // 假设地址是对象 { provinceCode, cityCode, districtCode, countyCode, townCode }
    selectedProvince.value = address.provinceCode?.toString() || ''
    handleProvinceChange(selectedProvince.value)

    nextTick(() => {
      selectedCity.value = address.cityCode?.toString() || ''
      handleCityChange(selectedCity.value)

      nextTick(() => {
        selectedDistrict.value = address.districtCode?.toString() || ''
        handleDistrictChange(selectedDistrict.value)

        nextTick(() => {
          selectedCounty.value = address.countyCode?.toString() || ''
          handleCountyChange(selectedCounty.value)

          nextTick(() => {
            selectedTown.value = address.townCode?.toString() || ''
          })
        })
      })
    })
  }

  deviceDialogVisible.value = true
}

// 保存设备
const saveDevice = () => {
  deviceFormRef.value?.validate(async (valid) => {
    if (!valid) return

    deviceBtnLoading.value = true

    if (selectedProvince.value || selectedCity.value || selectedDistrict.value) {
      const province = provinceList.value.find(p => p.code === selectedProvince.value)?.name || '';
      const city = cityOptions.value.find(c => c.code === selectedCity.value)?.name || '';
      const district = districtOptions.value.find(d => d.code === selectedDistrict.value)?.name || '';
      const county = countyOptions.value.find(c => c.code === selectedCounty.value)?.name || '';
      const town = townOptions.value.find(t => t.code === selectedTown.value)?.name || '';

      // 拼接成字符串，比如用空格或逗号分隔
      deviceForm.value.device_address = [province, city, district, county, town].filter(Boolean).join('-');
    }
    try {
      const api = deviceDialogType.value === 'create'
          ? '/api/device/createDevice'
          : '/api/device/updateDevice'
      const res = await axios.post(api, deviceForm.value)
      if (res.data.code === 200) {
        ElMessage.success(deviceDialogType.value === 'create' ? '新增成功' : '编辑成功')
        deviceDialogVisible.value = false
        fetchDeviceList()
      } else {
        ElMessage.error(res.data.msg || '操作失败')
      }
    } catch (error) {
      console.error('请求失败:', error)
      ElMessage.error('网络异常，请稍后重试')
    } finally {
      deviceBtnLoading.value = false
    }
  })
}

// 关闭弹窗
const closeDeviceDialog = () => {
  deviceDialogVisible.value = false
  deviceFormRef.value?.resetFields()
}

// 查看详情
const viewDeviceDetails = (row) => {
  detailData.value = { ...row }
  detailVisible.value = true
}

// 删除设备
const deleteDevice1 = (row) => {
  ElMessageBox.confirm(
      `确定要删除设备【${row.device_name}】吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(async () => {
    try {
      const res = await axios.post('/api/device/deleteDevice', { id: row.id })
      if (res.data.code === 200) {
        ElMessage.success('删除成功')
        fetchDeviceList()
      } else {
        ElMessage.error(res.data.msg || '删除失败')
      }
    } catch (error) {
      console.error('请求失败:', error)
      ElMessage.error('网络异常，请稍后重试')
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 批量删除设备
const deleteSelectedDevices = () => {
  const ids = multipleDeviceSelection.value.map(item => item.id)
  if (ids.length === 0) {
    ElMessage.warning('请选择要删除的设备')
    return
  }

  ElMessageBox.confirm(
      `确定要删除选中的 ${ids.length} 个设备吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(async () => {
    try {
      const res = await axios.post('/api/device/deleteDeviceByIds', { ids })
      if (res.data.code === 200) {
        ElMessage.success('批量删除成功')
        fetchDeviceList()
        multipleDeviceSelection.value = []
      } else {
        ElMessage.error(res.data.msg || '批量删除失败')
      }
    } catch (error) {
      console.error('请求失败:', error)
      ElMessage.error('网络异常，请稍后重试')
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 关闭详情弹窗
const closeDetail = () => {
  detailVisible.value = false
}

// 监听省市区变化，更新表单中的地址显示
watch([selectedProvince, selectedCity, selectedDistrict, selectedCounty, selectedTown], () => {
  if (deviceDialogVisible.value && deviceDialogType.value === 'create') {
    const province = provinceList.value.find(p => p.code === selectedProvince.value)?.name || ''
    const city = cityOptions.value.find(c => c.code === selectedCity.value)?.name || ''
    const district = districtOptions.value.find(d => d.code === selectedDistrict.value)?.name || ''
    const county = countyOptions.value.find(c => c.code === selectedCounty.value)?.name || ''
    const town = townOptions.value.find(t => t.code === selectedTown.value)?.name || ''

    // 更新表单中的地址显示（可选）
    deviceForm.value.device_address = [province, city, district, county, town].filter(Boolean).join(' ')
  }
})

// 确保 onMounted 执行
onMounted(() => {
  initAreaData()
  fetchDeviceList()
})
</script>

<style scoped>
.device-container {
  padding: 20px;
}
.filter-bar {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 8px;
  margin-bottom: 20px;
}
/* 可根据需求补充更多样式 */
</style>